/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.questionfeedback;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.message.rpc.NoteRpcServiceImpl;
import com.je.message.vo.CodeEnum;
import com.je.message.vo.NoteMsg;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * @ClassName
 * @Author wangchao
 * @Date 2022/7/11 0011 16:47
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/je/meta/questionFeedback")
public class QuestionFeedbackController extends AbstractPlatformController {

    @Autowired
    private NoteRpcServiceImpl noteRpcService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    /**
     * 验证码的时效key
     */
    private static final String CAPTCHA_KEY_TEMPLATE = "feedBackCaptcha/%s/%s";

    private final String URL = "https://suanbanyun.com/je/crm/questionFeedback/save";

    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public BaseRespResult sendCode(BaseMethodArgument param, HttpServletRequest request) {
        String phone = getStringParameter(request, "phone");
        String device = getStringParameter(request, "device");
        String userName = getStringParameter(request, "userName");
        if (Strings.isNullOrEmpty(phone)) {
            return BaseRespResult.errorResult("请输入您的手机号！");
        }

        String code = RandomUtil.randomNumbers(6);
        String timeout = systemSettingRpcService.findSettingValue("JE_SMS_TIMEOUT");
        String noteCount = systemSettingRpcService.findSettingValue("JE_SYS_NOTE_COUNT");
        String context = "您好，您的验证码为：" + code + "，验证码有效时长" + timeout + "秒，如非本人操作，请忽略此短信";
        try {
            NoteMsg noteMsg = new NoteMsg();
            noteMsg.setFromUser("系统");
            noteMsg.setToUser(userName);
            noteMsg.setContext(context);
            noteMsg.setPhoneNumber(phone);
            noteMsg.setFl("问题反馈");
            noteMsg.setMsgCode(code);
            int i = noteRpcService.sendNoteCode(noteMsg);
            if (i == CodeEnum.SUCCESS.getCode()) {
                return BaseRespResult.successResult("验证码发送成功！");
            } else if (i == CodeEnum._9000.getCode()) {
                return BaseRespResult.errorResult("手机号为空！");
            } else if (i == CodeEnum._9001.getCode()) {
                return BaseRespResult.errorResult("每日可发送验证码" + noteCount + "次!");
            } else if (i == CodeEnum._9002.getCode()) {
                return BaseRespResult.errorResult("验证码有效时长" + timeout + "秒，请勿重复发送验证码!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseRespResult.errorResult("发送失败，请联系管理员！");
        }

        return BaseRespResult.successResult("验证码发送成功！");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public BaseRespResult save(BaseMethodArgument param, HttpServletRequest request) {
        String phone = getStringParameter(request, "phone");
        String device = getStringParameter(request, "device");
        String code = getStringParameter(request, "code");
        if (Strings.isNullOrEmpty(phone)) {
            return BaseRespResult.errorResult("请输入您的手机号！");
        }

        String key = String.format(CAPTCHA_KEY_TEMPLATE, phone, code);
        if (!redisTemplate.hasKey(key)) {
            return BaseRespResult.errorResult("验证码错误或者已失效，请重新发送！");
        }
        if (!redisTemplate.opsForValue().get(key).toString().equals(code)) {
            return BaseRespResult.errorResult("验证码错误，请重新输入！");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone", getStringParameter(request, "phone"));
        jsonObject.put("device", getStringParameter(request, "device"));
        jsonObject.put("userName", getStringParameter(request, "userName"));
        jsonObject.put("customerName", getStringParameter(request, "customerName"));
        jsonObject.put("description", getStringParameter(request, "description"));
        jsonObject.put("repetition", getStringParameter(request, "repetition"));
        jsonObject.put("accessory", getStringParameter(request, "accessory"));
        jsonObject.put("title", getStringParameter(request, "title"));
        jsonObject.put("browserCode", getStringParameter(request, "browserCode"));
        jsonObject.put("browserName", getStringParameter(request, "browserName"));

        String json = String.valueOf(jsonObject);
        //生成httpclient，相当于该打开一个浏览器
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = null;
        HttpPost httpPost = new HttpPost(URL);
        NameValuePair pair1 = new BasicNameValuePair("param", json);
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(pair1);
        try {
            //创建代表请求体的对象（注意，是请求体）
            StringEntity requestEntity = new UrlEncodedFormEntity(pairs, "utf-8");
            //装填参数
            requestEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            //将请求体放置在请求对象当中
            httpPost.setEntity(requestEntity);
            //执行请求对象
            try {
                //第三步：执行请求对象，获取服务器发还的相应对象
                response = httpClient.execute(httpPost);
                //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
                if (response.getStatusLine().getStatusCode() == 200) {
                    //第五步：从相应对象当中取出数据，放到entity当中
                    HttpEntity entity = response.getEntity();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(entity.getContent()));
                    String result = reader.readLine();

                    JSONObject jsonResult = (JSONObject) JSON.parse(result);
                    if (!Boolean.parseBoolean(jsonResult.getString("success"))) {
                        throw new Exception(jsonResult.getString("message"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return BaseRespResult.errorResult(e.getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseRespResult.successResult("提交成功！");
    }
}
